<template>
  <div class="container">
    <div class="header">
      <div class="subtitle">坚持签到，获取更多奖励</div>
    </div>
    
    <!-- 日历 -->
    <div class="calendar-wrapper">
      <div class="calendar-header">
        <div class="calendar-nav">
          <div class="nav-btn" @click="prevMonth">
            <u-icon name="arrow-left" size="20" color="#606266"></u-icon>
          </div>
          <div class="current-month">{{ currentYear }}年{{ currentMonth }}月</div>
          <div class="nav-btn" @click="nextMonth">
            <u-icon name="arrow-right" size="20" color="#606266"></u-icon>
          </div>
        </div>
      </div>
      
      <div class="calendar-content">
        <!-- 星期标题 -->
        <div class="weekdays">
          <div class="weekday" v-for="day in weekDays" :key="day">{{ day }}</div>
        </div>
        
        <!-- 日期网格 -->
        <div class="days-grid">
          <div 
            class="day-item" 
            v-for="(day, index) in calendarDays" 
            :key="index"
            :class="{
              'other-month': day.isOtherMonth,
              'today': day.isToday,
              'signed': day.isSigned,
              'selected': day.isSelected
            }"
            @click="selectDate(day)"
          >
            <div class="day-number">{{ day.day }}</div>
            <div class="day-dot" v-if="day.isSigned"></div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="sign-btn-container">
      <div 
        class="sign-btn" 
        @click="signToday()" 
        v-if="canSignToday()"
        :class="{ 'loading': isSigningIn }"
      >
        <div class="btn-text">{{ isSigningIn ? '签到中...' : '立即签到' }}</div>
      </div>
      <div 
        class="sign-btn disabled" 
        v-else
      >
        <div class="btn-text">{{ getTodaySignedMessage() }}</div>
      </div>
    </div>
    
    <div class="statistics">
      <div class="stat-item">
        <div class="stat-value">{{ totalDays }}</div>
        <div class="stat-label">累计签到</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ currentMonthDays }}</div>
        <div class="stat-label">本月签到</div>
      </div>
      <div class="stat-item" v-if="consecutiveDays > 0">
        <div class="stat-value">{{ consecutiveDays }}</div>
        <div class="stat-label">连续签到</div>
      </div>
    </div>
    
    <div class="message-box" v-if="message">
      {{ message }}
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-overlay" v-if="isLoading">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
  </div>
</template>

<script>
import request from '@/util/request.js';

export default {
  data() {
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth() + 1;
    const currentDay = today.getDate();
    
    return {
      currentDay: currentDay,
      currentMonth: currentMonth,
      currentYear: currentYear,
      selectedDate: null,
      totalDays: 0,
      currentMonthDays: 0,
      consecutiveDays: 0,
      todaySigned: false,
      message: '',
      signedDates: [], // 存储已签到的日期字符串，格式：YYYY-MM-DD
      weekDays: ['日', '一', '二', '三', '四', '五', '六'],
      calendarDays: [],
      isLoading: false,
      isSigningIn: false,
      userId: null
    };
  },
  mounted() {
    this.initPage();
  },
  methods: {
    // 初始化页面
    async initPage() {
      try {
        // 获取用户ID（从userInfo中获取）
        const userInfo = uni.getStorageSync('userInfo');
        console.log('获取到的userInfo:', userInfo);
        
        if (userInfo && userInfo.userId) {
          this.userId = userInfo.userId;
          console.log('成功获取userId:', this.userId);
        } else {
          console.log('userInfo不存在或userId不存在');
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }, 1500);
          return;
        }
        
        // 加载签到数据
        await this.loadSignInInfo();
        // 生成日历
        this.generateCalendar();
      } catch (error) {
        console.error('初始化页面失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 从后端加载签到信息
    async loadSignInInfo() {
      this.isLoading = true;
      try {
        const response = await request({
          url: `/user-service/signin/info/${this.userId}`,
          method: 'GET'
        });
        
        if (response.success && response.data && response.data.signInInfo) {
          const signInInfo = response.data.signInInfo;
          this.totalDays = signInInfo.totalDays || 0;
          this.currentMonthDays = signInInfo.currentMonthDays || 0;
          this.consecutiveDays = signInInfo.consecutiveDays || 0;
          this.todaySigned = signInInfo.todaySigned || false;
          this.signedDates = signInInfo.signedDates || [];
          
          // 更新当前年月（如果后端返回了的话）
          if (signInInfo.currentYear && signInInfo.currentMonth) {
            this.currentYear = signInInfo.currentYear;
            this.currentMonth = signInInfo.currentMonth;
          }
        }
      } catch (error) {
        console.error('加载签到信息失败:', error);
        // 如果是网络错误，使用本地数据作为备用
        this.loadLocalSignedData();
      } finally {
        this.isLoading = false;
      }
    },
    
    // 生成日历数据
    generateCalendar() {
      const year = this.currentYear;
      const month = this.currentMonth;
      const today = new Date();
      const todayStr = this.formatDate(today);
      
      // 获取当月第一天和最后一天
      const firstDay = new Date(year, month - 1, 1);
      const lastDay = new Date(year, month, 0);
      
      // 获取第一天是星期几
      const firstDayWeek = firstDay.getDay();
      
      // 获取上个月的最后几天
      const prevMonth = new Date(year, month - 1, 0);
      const prevMonthDays = prevMonth.getDate();
      
      const days = [];
      
      // 添加上个月的日期
      for (let i = firstDayWeek - 1; i >= 0; i--) {
        const day = prevMonthDays - i;
        const date = new Date(year, month - 2, day);
        days.push({
          day: day,
          date: date,
          dateStr: this.formatDate(date),
          isOtherMonth: true,
          isToday: false,
          isSigned: this.signedDates.includes(this.formatDate(date)),
          isSelected: false
        });
      }
      
      // 添加当月的日期
      for (let day = 1; day <= lastDay.getDate(); day++) {
        const date = new Date(year, month - 1, day);
        const dateStr = this.formatDate(date);
        days.push({
          day: day,
          date: date,
          dateStr: dateStr,
          isOtherMonth: false,
          isToday: dateStr === todayStr,
          isSigned: this.signedDates.includes(dateStr),
          isSelected: false
        });
      }
      
      // 添加下个月的日期，补齐6行
      const remainingDays = 42 - days.length;
      for (let day = 1; day <= remainingDays; day++) {
        const date = new Date(year, month, day);
        days.push({
          day: day,
          date: date,
          dateStr: this.formatDate(date),
          isOtherMonth: true,
          isToday: false,
          isSigned: this.signedDates.includes(this.formatDate(date)),
          isSelected: false
        });
      }
      
      this.calendarDays = days;
    },
    
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 上一个月
    prevMonth() {
      if (this.currentMonth === 1) {
        this.currentMonth = 12;
        this.currentYear--;
      } else {
        this.currentMonth--;
      }
      this.generateCalendar();
    },
    
    // 下一个月
    nextMonth() {
      if (this.currentMonth === 12) {
        this.currentMonth = 1;
        this.currentYear++;
      } else {
        this.currentMonth++;
      }
      this.generateCalendar();
    },
    
    // 选择日期
    selectDate(day) {
      if (day.isOtherMonth) return;
      
      // 清除之前的选中状态
      this.calendarDays.forEach(d => d.isSelected = false);
      // 设置当前选中
      day.isSelected = true;
      this.selectedDate = day.dateStr;
      
      // 如果选择的是今天，可以进行签到操作
      if (day.isToday && this.canSignToday()) {
        this.signToday();
      }
    },
    
    // 签到操作
    async signToday() {
      if (!this.canSignToday() || this.isSigningIn) return;
      
      this.isSigningIn = true;
      try {
        const response = await request({
          url: `/user-service/signin/sign/${this.userId}`,
          method: 'POST'
        });
        
        if (response.success && response.data && response.data.result) {
          const result = response.data.result;
          
          if (result.success) {
            // 签到成功，更新本地数据
            const signInInfo = result.signInInfo;
            this.totalDays = signInInfo.totalDays || 0;
            this.currentMonthDays = signInInfo.currentMonthDays || 0;
            this.consecutiveDays = signInInfo.consecutiveDays || 0;
            this.todaySigned = signInInfo.todaySigned || false;
            this.signedDates = signInInfo.signedDates || [];
            
            // 重新生成日历以显示签到状态
            this.generateCalendar();
            
            // 显示成功消息
            this.message = result.message || '签到成功！';
            setTimeout(() => {
              this.message = '';
            }, 3000);
            
            // 保存到本地存储作为备用
            this.saveLocalSignedData();
          } else {
            // 签到失败（比如今日已签到）
            this.message = result.message || '签到失败';
            setTimeout(() => {
              this.message = '';
            }, 3000);
          }
        }
      } catch (error) {
        console.error('签到失败:', error);
        uni.showToast({
          title: '签到失败，请重试',
          icon: 'none'
        });
      } finally {
        this.isSigningIn = false;
      }
    },
    
    // 检查今天是否可以签到
    canSignToday() {
      return !this.todaySigned;
    },
    
    // 获取今天签到状态消息
    getTodaySignedMessage() {
      return "今日已签到";
    },
    
    // 加载本地签到数据（备用方案）
    loadLocalSignedData() {
      try {
        const savedData = uni.getStorageSync('signedDates');
        if (savedData) {
          const localData = JSON.parse(savedData);
          this.signedDates = localData.signedDates || [];
          this.totalDays = localData.totalDays || 0;
          this.currentMonthDays = localData.currentMonthDays || 0;
          this.consecutiveDays = localData.consecutiveDays || 0;
          this.todaySigned = localData.todaySigned || false;
        }
      } catch (e) {
        console.error('加载本地签到数据失败:', e);
      }
    },
    
    // 保存签到数据到本地存储（备用方案）
    saveLocalSignedData() {
      try {
        const dataToSave = {
          signedDates: this.signedDates,
          totalDays: this.totalDays,
          currentMonthDays: this.currentMonthDays,
          consecutiveDays: this.consecutiveDays,
          todaySigned: this.todaySigned,
          lastUpdate: new Date().toISOString()
        };
        uni.setStorageSync('signedDates', JSON.stringify(dataToSave));
      } catch (e) {
        console.error('保存本地签到数据失败:', e);
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
  background-color: #f8f9fa;
  min-height: auto;
  padding-bottom: 40px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 20px;
}

/* .title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
} */

.subtitle {
  font-size: 14px;
  color: #888;
}

/* 日历样式 */
.calendar-wrapper {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;
}

.calendar-header {
  background: #fff;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.calendar-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.nav-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.nav-btn:hover {
  background-color: #f5f7fa;
}

.current-month {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.calendar-content {
  padding: 0 20px 20px;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 0;
  margin-bottom: 8px;
  padding-top: 16px;
}

.weekday {
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  color: #909399;
  padding: 8px 0;
}

.days-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.day-item {
  position: relative;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.day-item:hover:not(.other-month) {
  background-color: #f0f9ff;
}

.day-item.other-month {
  color: #c0c4cc;
  cursor: not-allowed;
}

.day-item.today {
  background-color: #409eff;
  color: #fff;
  font-weight: 600;
}

.day-item.signed {
  background-color: #67c23a;
  color: #fff;
}

.day-item.selected {
  background-color: #409eff;
  color: #fff;
}

.day-number {
  font-size: 14px;
  position: relative;
  z-index: 2;
}

.day-dot {
  position: absolute;
  bottom: 4px;
  right: 4px;
  width: 6px;
  height: 6px;
  background-color: #f56c6c;
  border-radius: 50%;
  z-index: 3;
}

.day-item.signed .day-dot {
  background-color: #fff;
}

.sign-btn-container {
  margin: 25px 0;
}

.sign-btn {
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  padding: 15px 0;
  border-radius: 50px;
  text-align: center;
  font-weight: bold;
  font-size: 18px;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.sign-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 20px rgba(64, 158, 255, 0.4);
}

.sign-btn.disabled {
  background: linear-gradient(135deg, #cccccc, #a0a0a0);
  cursor: not-allowed;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.sign-btn.disabled:hover {
  transform: none;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.btn-text {
  position: relative;
  display: inline-block;
}

.btn-text::after {
  content: "→";
  position: absolute;
  margin-left: 8px;
  opacity: 0;
  transition: opacity 0.3s, transform 0.3s;
}

.sign-btn:not(.disabled):hover .btn-text::after {
  opacity: 1;
  transform: translateX(5px);
}

.statistics {
  display: flex;
  justify-content: space-around;
  background-color: white;
  border-radius: 16px;
  padding: 20px 15px;
  margin-bottom: 20px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 26px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #888;
}

.message-box {
  position: fixed;
  top: 20%;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 15px 25px;
  border-radius: 50px;
  font-size: 16px;
  text-align: center;
  animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
  z-index: 100;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translate(-50%, -10px); }
  to { opacity: 1; transform: translate(-50%, 0); }
}

@keyframes fadeOut {
  from { opacity: 1; transform: translate(-50%, 0); }
  to { opacity: 0; transform: translate(-50%, -10px); }
}

 .loading-overlay {
   position: fixed;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background-color: rgba(0, 0, 0, 0.5);
   display: flex;
   flex-direction: column;
   align-items: center;
   justify-content: center;
   z-index: 1000;
 }

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

 .loading-text {
   color: white;
   font-size: 16px;
   margin-top: 16px;
   text-align: center;
 }

.sign-btn.loading {
  opacity: 0.7;
  cursor: not-allowed;
}

.sign-btn.loading:hover {
  transform: none;
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
}
</style>
